package com.lucy.viewer.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import com.lucy.viewer.constant.ViewerConst;
import com.lucy.viewer.event.FileCreatedEvent;
import com.lucy.viewer.params.ViewerFile;
import com.lucy.viewer.service.EditService;
import com.lucy.viewer.service.ViewerFileService;
import com.lucy.viewer.utils.ViewerFileCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Controller
@RequestMapping("viewer")
@Api(tags = "文档新建服务")
@AllArgsConstructor
public class EditorController {
    EditService editService;

    ViewerFileService fileService;

    ApplicationContext context;

    @ApiIgnore
    @Deprecated
    @RequestMapping("editor")
    @ApiOperation(value = "编辑器",notes = "")
    public ModelAndView markdownEditor(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
        // 获取文件名
        String fileType = FileNameUtil.extName(fileName);
        if (Validator.isEmpty(fileType)){
            throw new RuntimeException("文件名不符合规范");
        }
        // 基础默认路径
        String baseDir = ViewerConst.tempFilePath();
        // 空文件创建
        ViewerFile file = new ViewerFile();
        // 文件类型
        file.setFileType(fileType);
        file.setFileName(fileName);
        file.setTitle(fileName);
        // 随机key
        String key = IdUtil.fastSimpleUUID();
        file.setKey(key);
        // 获取文件路径
        String filePath = baseDir + key + '.' + fileType;
        // 创建文件
        FileUtil.touch(filePath);
        file.setPath(filePath);
        // 文件访问链接
        file.setUrl("/viewer/download/"+key);
        // 执行创建事件 -- 并刷新 viewerFile 值
        file = fileService.createViewerFile(file);

        context.publishEvent(new FileCreatedEvent(this,file));
        // 返回
        return editService.loadEditView(file.getKey(),response);
    }
}
